package dbmanager

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

type AccessSrv struct {
	Id 				int64
	Domain 			string
	AccessPort 		int
	RpcPort 		int
	Version 		int
	Created         int64
	Updated         int64
	Status          int
}

func (w *AccessSrv) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *AccessSrv) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *AccessSrv) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *AccessSrv) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}

	return nil
}

func init()  {
	orm.RegisterModel(new(AccessSrv))
}

func (w *AccessSrv) SelectWithStatus(offset int, limit int, status int, domain string, version int) ([]*AccessSrv, error) {
	var servers []*AccessSrv

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)

	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if domain != mysqldb.SelectStrAll {
		qs = qs.Filter("domain__istartswith", domain)
	}
	if version != mysqldb.SelectIntAll {
		qs = qs.Filter("version", version)
	}
	qs.OrderBy("-version")

	_, err := qs.All(&servers)
	if err != nil {
		return nil, err
	}

	return servers, nil
}

func (w *AccessSrv) SelectCount(status int, domain string, version int) (int64, error) {

	qs := orm.NewOrm().QueryTable(w)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if domain != mysqldb.SelectStrAll {
		qs = qs.Filter("domain__istartswith", domain)
	}
	if version != mysqldb.SelectIntAll {
		qs = qs.Filter("version", version)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}

	return count, nil
}